package io.github.shenbinglife.springboot2.layui.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JsonUtils
 *
 * @author shenbing
 * @date 2021/4/12 22:10
 */
public class JsonUtils {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error to convert object to json string", e);
        }
    }

    public static <T> T fromJson(String json, Class<T> clz) {
        try {
            return objectMapper.readValue(json, clz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error to read object from json string", e);
        }
    }

    public static <T> List<T> fromJsonAsList(String json, Class<T> clz) {
        try {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, clz);
            return objectMapper.readValue(json, javaType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error to read object from json string", e);
        }
    }

    public static <T, K> Map<T, K> fromJsonAsMap(String json, Class<T> keyClz, Class<K> valClz) {
        try {
            JavaType javaType = objectMapper.getTypeFactory().constructMapType(HashMap.class, keyClz, valClz);
            return objectMapper.readValue(json, javaType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error to read object from json string", e);
        }
    }
}
